import java.util.Random;

/**
 * Created by Administrator on 2017/2/5.
 */
public class SortTestHelper {
    /**
     *
     * @param length 数组范围；
     * @param rangeL
     * @param rangeR
     * @return 返回长度为length，每个元素为[rangeL,rangeR]之间的随机数的数组
     * */
    public static int[] generateRandomArray(int length,int rangeL,int rangeR){
        int[] array = new int[length];
        Random random = new Random();
        int rangeLength = rangeR - rangeL + 1;
        if (rangeLength <= 0) {
            return null;
        }
        for (int i = 0; i < array.length; i++) {
            array[i] = random.nextInt(rangeLength) + rangeL;
//            System.out.print(i + ":" + array[i] + " ");
            System.out.print(array[i] + " ");
        }
        return array;
    }


    /**
     *
     * 生成一个近乎有序的长度为length的数组
     *
     *
     * */
    public static int[] generateNearlyOrderedArray(int length,int swapTimes){
        int[] array = new int[length];
        for (int i = 0; i < array.length; i++) {
            array[i] = i;
        }

        Random random = new Random();
        //随机生成两个数 交换以这两个数为下标的数组元素
        for (int i = 0; i < swapTimes; i++) {
            int first = random.nextInt(length);
            int second = random.nextInt(length);
            swap(array,first,second);
        }

        for (int i = 0; i < array.length; i++) {
            System.out.print(array[i] + " ");
        }
        return array;
    }

    private static void swap(int[] array, int first, int second) {
        if (first < 0 || first >= array.length || second < 0 || second >= array.length) {
            throw new IndexOutOfBoundsException();
        }
        int temp = array[first];
        array[first] = array[second];
        array[second] = temp;
    }

    public static void main(String[] args){
//        SortTestHelper.generateRandomArray(30,1,3);
        SortTestHelper.generateNearlyOrderedArray(30,5);
    }
}
